package cn.wolfcode.car.business.service.impl;


import cn.wolfcode.car.base.web.advice.GlobalExceptionHandler;
import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.query.ServiceItemQuery;
import cn.wolfcode.car.business.service.IBpmnService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class ServiceItemServiceImpl implements IServiceItemService {

    @Autowired
    private ServiceItemMapper serviceItemMapper;
    @Autowired
    private ICarPackageAuditService carPackageAuditService;
    @Autowired
    private IBpmnService bpmnService;
    @Autowired
    private RuntimeService runtimeService;

    @Override
    public TablePageInfo<ServiceItem> query(ServiceItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<ServiceItem>(serviceItemMapper.selectForList(qo));
    }


    @Override
    public void save(ServiceItem serviceItem) {
        // 如果是套餐,设置审核状态为初始化
        if (ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage())){
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        } else if (ServiceItem.CARPACKAGE_NO.equals(serviceItem.getCarPackage())) {
            // 如果不是套餐,设置审核状态为无需审核
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_NO_REQUIRED);
        }
        // 设置销售状态为下架,时间为当前时间
        serviceItem.setSaleStatus(ServiceItem.SALESTATUS_OFF);
        serviceItem.setCreateTime(new Date());
        serviceItemMapper.insert(serviceItem);
    }

    @Override
    public ServiceItem get(Long id) {
        return serviceItemMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(ServiceItem serviceItem) {
        ServiceItem ser = this.get(serviceItem.getId());
        if (ServiceItem.SALESTATUS_ON.equals(ser.getSaleStatus())) {
            throw new BusinessException("已上架,不能编辑");
        }
        if (ServiceItem.CARPACKAGE_YES.equals(ser.getCarPackage()) &&
                ServiceItem.AUDITSTATUS_AUDITING.equals(ser.getAuditStatus())) {
            throw new BusinessException("服务项处于审核中状态,不能编辑");
        }
        // 是套餐且审核通过
        if (ServiceItem.CARPACKAGE_YES.equals(ser.getCarPackage()) &&
                ServiceItem.AUDITSTATUS_APPROVED.equals(ser.getAuditStatus())) {
            // 初始化
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        } else {
            serviceItem.setAuditStatus(ser.getAuditStatus());
        }

        if (ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage())) {
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        } else {
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_NO_REQUIRED);
        }
        serviceItem.setSaleStatus(ServiceItem.SALESTATUS_OFF);
        serviceItemMapper.updateByPrimaryKey(serviceItem);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            serviceItemMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<ServiceItem> list() {
        return serviceItemMapper.selectAll();
    }

    @Override
    public void saleOn(Long id) {
        ServiceItem serviceItem = this.get(id);
        if (ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage()) &&
                !ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus())
        ) {
            throw new BusinessException("是套餐,需要审核通过才能上架");
        }
        serviceItemMapper.changeSaleStatus(id,ServiceItem.SALESTATUS_ON);
    }

    @Override
    public void saleOff(Long id) {
        serviceItemMapper.changeSaleStatus(id,ServiceItem.SALESTATUS_OFF);
    }

    @Override
    public void startAudit(Long id, Long bpmnInfoId, Long director, Long finance, String info) {
        // 校验
        ServiceItem serviceItem = this.get(id);
        if (serviceItem.getSaleStatus().equals(ServiceItem.SALESTATUS_ON)// 处于上架状态
                || serviceItem.getCarPackage().equals(ServiceItem.CARPACKAGE_NO)// 非套餐
                || serviceItem.getAuditStatus().equals(ServiceItem.AUDITSTATUS_AUDITING)// 处于审核中
                || serviceItem.getAuditStatus().equals(ServiceItem.AUDITSTATUS_APPROVED)// 处于审核通过
                || serviceItem.getAuditStatus().equals(ServiceItem.AUDITSTATUS_NO_REQUIRED))// 无需审核
        {
            throw new BusinessException("非法操作");
        }
        CarPackageAudit audit = new CarPackageAudit();
        audit.setCreateTime(new Date()); // 创建时间
        audit.setAuditorId(director);// 审核人
        audit.setBpmnInfoId(bpmnInfoId); // 流程
        audit.setCreator(ShiroUtils.getUser().getUserName()); // 创建人当前登录用户
        audit.setInfo(info); // 备注
        audit.setServiceItemId(id); // 套餐ID
        audit.setServiceItemName(serviceItem.getName()); // 套餐名称
        audit.setServiceItemInfo(serviceItem.getInfo()); // 套餐备注
        audit.setServiceItemPrice(serviceItem.getDiscountPrice()); // 套餐折扣价
        carPackageAuditService.save(audit); // 保存

        Map<String,Object> params = new HashMap<>(); // 传入条件
        params.put("director",director);
        if (finance != null) {
            params.put("finance",finance);
        }
        params.put("discountPrice",serviceItem.getDiscountPrice().longValue());

        // 获取bpmnInfo流程对象
        BpmnInfo bpmnInfo = bpmnService.get(bpmnInfoId);
        // 启动流程
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(bpmnInfo.getActProcessKey(), String.valueOf(audit.getId()), params);
        audit.setInstanceId(processInstance.getId()); // 关联流程实例ID
        carPackageAuditService.update(audit); // 更新内容
        serviceItemMapper.changeAuditStatus(id,ServiceItem.AUDITSTATUS_AUDITING); // 更新审核状态
    }
}
